package com.chenzhou.dao;

import com.chenzhou.common.BaseDAO;
import com.chenzhou.common.DBuitl;
import com.chenzhou.entity.ProductEntity;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

//生成测试的快捷键 ctrl+shift+T
@Repository
public class ProductDAOImpl extends BaseDAO<ProductEntity>{

    @Override
    protected List<ProductEntity> resultToList(ResultSet rs) throws SQLException {

        List<ProductEntity> list = new ArrayList<>();
        while(rs.next())
        {
            ProductEntity p = new ProductEntity();
            p.setPid(rs.getInt("pid"));
            p.setPname(rs.getString("pname"));
            p.setPprice(rs.getFloat("pprice"));
            p.setPnum(rs.getInt("pnum"));
            list.add(p);
        }
        return list;
    }

    /**
     * 查询商品信息
     * @return
     */
    public List<ProductEntity> queryAll(){
        String sql = "select * from product";
        return this.execute_Query(sql,null);
    }


    public ProductEntity queryByID(Integer pid){
        String sql = "select * from product where pid = ?";
        Object[] objects = new Object[]{pid};
        List<ProductEntity> list = this.execute_Query(sql,objects);
        if(list.size()>0){
            return list.get(0);
        }else{
            return null;
        }
    }

    /***
     * 添加商品信息
     * @param p
     * @return
     */
    public int add_product(ProductEntity p){
        String sql = "insert into product values(null,?,?,?)";
        Object[] objects = new Object[]{
                p.getPname(),
                p.getPprice(),
                p.getPnum()
        };
        return this.execute_Modify(sql,objects);
    }

    /***
     * 修改商品信息
     * @param p
     * @return
     */
    public int update_product(ProductEntity p){
        String sql = "update product set pname=?,pprice=?,pnum=? where pid=?";
        Object[] objects = new Object[]{
                p.getPname(),
                p.getPprice(),
                p.getPnum(),
                p.getPid()
        };
        return this.execute_Modify(sql,objects);
    }

    /***
     * 删除商品信息
     * @param pid
     * @return
     */
    public int delete_product(Integer pid){
        String sql = "delete from product where pid = ?";
        Object[] objects = new Object[]{pid};
        return this.execute_Modify(sql,objects);
    }
}
